const log4js = require('koa-log4');
const logger = log4js.getLogger('routes::site');
const mongodb = require('mongodb');
const ObjectId = mongodb.ObjectId;
const router = require('koa-router')();
exports = module.exports = router;

const CryptoJS = require("crypto-js");
const AES = require("crypto-js/aes");
const _ = require('lodash');
const util = require(global.prefixPath + '/commons/util');
const site_service = require(global.prefixPath + '/services/site');
const info_service = require(global.prefixPath + '/services/info');
const staff_service = require(global.prefixPath + '/services/staff');

const nconf = require('nconf');
const jwt = require('jsonwebtoken');
const cookie = require('cookie');

router.get('/sites', async (ctx, next) => {
    try {
        let result = await site_service.findAll();
        ctx.body = result;
    } catch (err) {
        throw err;
    }
});

router.get('/site/:id', async (ctx, next) => {
    try {
        let site_id = ctx.params.id;
        let result = await site_service.findById(site_id);
        // 解密密码
        let bytes = AES.decrypt(result.admin.password, ctx.app.secret);
        let plaintext = bytes.toString(CryptoJS.enc.Utf8);
        result.admin.password = plaintext;
        ctx.body = result;
    } catch (err) {
        throw err;
    }
});

router.post('/site', async (ctx, next) => {
    try {
        let site = ctx.request.body;
        let password = site.admin.password;
        // 加密密码
        let ciphertext = AES.encrypt(password, ctx.app.secret).toString();
        site.admin.password = ciphertext;
        let result = await site_service.insert(site);
        ctx.body = {
            result: result
        };
    } catch (err) {
        throw err;
    }
});

router.put('/site/:id', async (ctx, next) => {
    try {
        let site = ctx.request.body;
        site._id = new ObjectId(ctx.params.id);
        let password = site.admin.password;
        // 加密密码
        let ciphertext = AES.encrypt(password, ctx.app.secret).toString();
        site.admin.password = ciphertext;

        let result = await site_service.save(site);
        ctx.body = {
            result: result
        };
    } catch (err) {
        throw err;
    }
});

/**
 * 修改站点管理员登陆密码
 */
router.put('/site/:id/admin/password', async (ctx, next) => {
    try {
        let site = ctx.request.body;
        site._id = new ObjectId(ctx.params.id);
        let result = await site_service.save(site);

        ctx.body = {
            result: result
        };
    } catch (err) {
        throw err;
    }
});


/**
 * 站点管理员登陆
 */
router.post('/site/:id/admin/login', async (ctx, next) => {
    try {
        let site_id = ctx.params.id;
        let oid = new ObjectId(site_id);

        let admin = ctx.request.body;
        let site = await site_service.findById(site_id, {admin: 1});
        console.log('this is site ', admin);
        // 解密密码
        let bytes = AES.decrypt(site.admin.password, ctx.app.secret);
        let plaintext = bytes.toString(CryptoJS.enc.Utf8);
        console.log('plaintext', plaintext)
        let result = {};

        if (admin.username === site.admin.username && admin.password === plaintext) {
            console.log('用户密码验证正常')
            let app = ctx.app;
            var token = jwt.sign({
                exp: Math.floor(Date.now() / 1000) + parseInt(nconf.get('jwt').expiretime),
                admin: admin.username,
                site: site_id
            }, app.secret);
            console.log(token);
            // cookie中也种上token，方便页面后台渲染时就可以获取登陆状态，避免由ajax再次获取会刷新页面
            ctx.res.setHeader('set-cookie', cookie.serialize('access_token', token, {
                httpOnly: true,
                maxAge: parseInt(nconf.get('jwt').expiretime)
            }));
            result = {
                ok: true,
                token: token
            };
        } else {
            result.err = true;
            result.msg = "用户名或者密码错误！"
        }
        if (result.err) {
            ctx.status = 400
        }
        ctx.body = {
            result: result
        };

    } catch (err) {
        throw err;
    }
});

/**
 * 下线站点
 */
router.put('/site/:id/offline', async (ctx, next) => {
    try {
        let site_id = ctx.params.id;
        let oid = new ObjectId(site_id);
        let update = {
            query: {_id: oid},
            update: {$set: {status: `offline`}}
        };
        let result = await site_service.findAndModify(update.query, update.update);
        ctx.body = {
            result: result
        };
    } catch (err) {
        throw err;
    }
});


/**
 * 上线站点
 */
router.put('/site/:id/online', async (ctx, next) => {
    try {
        let site_id = ctx.params.id;
        let oid = new ObjectId(site_id);
        let update = {
            query: {_id: oid},
            update: {$set: {status: `online`}}
        };
        let result = await site_service.findAndModify(update.query, update.update);
        ctx.body = {
            result: result
        };
    } catch (err) {
        throw err;
    }
});

/**
 * 设置站点广告
 */
router.put('/site/:id/adsenses', async (ctx, next) => {
    try {
        let site_id = ctx.params.id;
        let oid = new ObjectId(site_id);
        let adsenses = ctx.request.body;
        let update = {
            query: {_id: oid},
            update: {$set: {adsenses: adsenses}}
        };

        let result = await site_service.findAndModify(update.query, update.update);
        ctx.body = result;
    } catch (err) {
        throw err;
    }
});

/**
 * 查询站点广告信息
 */
router.get('/site/:id/adsenses', async (ctx, next) => {
    try {
        let site_id = ctx.params.id;
        let fields = {adsenses: 1, _id: 0};
        let adsenses = (await site_service.findById(site_id, fields)).adsenses;

        let allids = [];
        for (let key in adsenses) {
            allids = allids.concat(adsenses[key]);
        }
        allids = util.toObjectId(allids);

        let allads = await info_service.findByIds(allids);

        // 组合数据
        for (let key in adsenses) {
            // TODO: 这样去重 但是有些场景是可以重复的吧

            let ads = _.filter(allads, (val) => {
                return _.indexOf(adsenses[key], val._id.toString()) >= 0;
            });

            // _.remove(allads, (val) => {
            //     return _.indexOf(adsenses[key], val._id.toString()) >= 0;
            // });

            adsenses[key] = ads;
        }

        ctx.body = adsenses;
    } catch (err) {
        throw err;
    }
});

/**
 * 查询站点员工信息
 */
router.get('/site/:id/staffs', async (ctx, next) => {
    try {
        let site_id = ctx.params.id;
        let fields = {adsenses: 1, _id: 0};
        let staffs = (await staff_service.findBySite(site_id, fields));
        ctx.body = staffs;
    } catch (err) {
        throw err;
    }
});


/**
 * 删除信息
 */
router.delete('/site/:id', async (ctx, next) => {
    try {
        let site_id = ctx.params.id;
        let result = await site_service.delById(site_id);
        ctx.body = result;
    } catch (err) {
        throw err;
    }
});
